<style rel="stylesheet/scss" lang="scss" scoped>
</style>

<template>
    <div class="container">
        <el-card shadow="hover" style="padding:0">

            <el-form ref="searchForm" :inline="true" :model="searchForm" size="medium" label-width="120px">
                <el-card class="operate_container" shadow="never">
                    <div class="wrapper">
                        <!-- <div><i class="el-icon-tickets" style="margin-right: 10px;"></i>数据列表</div> -->
                        <!-- 关键字模糊检索 -->
                        <div class="searchKeyword">
                            <el-form-item prop="keyword">
                                <el-input placeholder="请输入检索关键字" v-model="searchForm.keyword" clearable @clear="handleResetSearch('searchForm')">
                                    <el-button slot="append" icon="el-icon-search" @click="handleSearch()"></el-button>
                                </el-input>
                            </el-form-item>
                        </div>
                        <!-- 操作按钮 -->
                        <div>
                            <el-button icon="el-icon-chat-dot-square" size="medium" @click="handleOpenMessageDialog">即时消息</el-button>
                            <el-button icon="el-icon-tickets" size="medium" @click="handleResetPassword">重置密码</el-button>

                            <el-button v-if="isAuth(['admin:systemuser:save', 'admin:systemuser:update'])" type="primary" icon="el-icon-plus" size="medium" circle @click="addOrUpdateVisible"></el-button>
                            <el-button v-if="isAuth(['admin:systemuser:delete'])" type="danger" icon="el-icon-delete" size="medium" circle @click="handleDelete"></el-button>
                            <el-button type="primary" icon="el-icon-refresh" size="medium" circle @click="handleResetSearch('searchForm')"></el-button>
                            <el-button type="primary" icon="el-icon-search" size="medium" circle @click="searchVisible = !searchVisible"></el-button>
                        </div>
                    </div>
                </el-card>

                <!-- 组合条件检索 -->
                <el-card class="filter_container" shadow="never" v-show="searchVisible">
                    <div style="margin-top: 15px">
                            <el-form-item label="用户名" prop="username">
                                <el-input v-model="searchForm.username" clearable placeholder="用户名"></el-input>
                            </el-form-item>
                            <el-form-item label="手机号" prop="mobile">
                                <el-input v-model="searchForm.mobile" clearable placeholder="手机号码"></el-input>
                            </el-form-item>
                            <el-form-item label="姓名" prop="realname">
                                <el-input v-model="searchForm.realname" clearable placeholder="姓名"></el-input>
                            </el-form-item>
                            <el-form-item label="邮箱" prop="email">
                                <el-input v-model="searchForm.email" clearable placeholder="邮箱"></el-input>
                            </el-form-item>
                            <el-form-item label="状态" prop="status">
                                <el-select style="width: 100%;" v-model="searchForm.status" placeholder="状态">
                                    <el-option label="正常" :value="1"></el-option>
                                    <el-option label="禁用" :value="0"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label=" ">
                                <el-button type="primary" @click="handleSearch()" size="medium">搜索</el-button>
                                <el-button @click="handleResetSearch('searchForm')" size="medium">重置</el-button>
                            </el-form-item>
                    </div>
                </el-card>
             </el-form>

            <!-- 表格 -->
            <el-table
                ref="table" size="small" empty-text="暂无数据"
                element-loading-text="给我一点时间"
                fit stripe border highlight-current-row
                v-loading="dataListLoading"
                :data="dataList"
                :header-cell-style="{'padding-top': '10px', 'height': '50px', 'color': '#515A6E', 'background-color': '#f8f8f9'}"
                @selection-change="handleSelection">
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column type="index" width="55" align="center"></el-table-column>

                <el-table-column label="头像" align="center" width="80">
                    <template slot-scope="scope">
                        <el-avatar size="small" :src="scope.row.avatar"></el-avatar>
                    </template>
                </el-table-column>
                <el-table-column label="姓名" prop="realname" align="center"/>
                <el-table-column label="用户名" prop="username" align="center"/>
                <el-table-column label="手机号码" prop="mobile" align="center"/>
                <el-table-column label="邮件地址" prop="email" column-key="email" show-overflow-tooltip min-width="150px" align="center"/>
                <el-table-column label="性别" width="80px" align="center">
                    <template slot-scope="scope">
                        <el-tag type="primary" size="small" v-if="scope.row.sex === '男'">男</el-tag>
                        <el-tag type="success" size="small" v-else-if="scope.row.sex === '女'">女</el-tag>
                        <el-tag type="danger" size="small" v-else>未知</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="状态" width="80px" align="center">
                    <template slot-scope="scope">
                        <el-tag type="success" size="small" v-if="scope.row.status === 1">正常</el-tag>
                        <el-tag type="danger" size="small" v-else>禁用</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="超级管理员" align="center">
                    <template slot-scope="scope">
                        <el-tag type="success" size="small" v-if="scope.row.superAdmin === 1">是</el-tag>
                        <el-tag type="danger" size="small" v-else>否</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" prop="ctime" align="center" width="150"/>
                <el-table-column label="最后更新时间" prop="utime" align="center" width="150"/>

                <el-table-column label="操作" width="200px" align="center" fixed="right">
                    <template slot-scope="scope">
                        <div class="table_action">
                            <el-button size="small" @click="handleOpenSetRoleDialog(scope.row)">设置角色</el-button>
                            <el-button v-if="isAuth(['admin:systemuser:save', 'admin:systemuser:update'])" type="primary" icon="el-icon-edit" circle size="small" @click="addOrUpdateVisible(scope.row)"></el-button>
                            <el-button v-if="isAuth(['admin:systemuser:delete'])"  type="danger" icon="el-icon-delete" circle size="small" @click="handleDelete(scope.row)"></el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页工具栏 -->
            <div class="pagination">
                <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="searchForm.page"
                        :page-sizes="[10, 20, 30, 50, 100, 200]"
                        :page-size="searchForm.limit"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="totalPage">
                </el-pagination>
            </div>

            <!-- 窗口 -->
            <el-dialog
                :title="!form.id ? '新增' : '修改'"
                :visible.sync="visible" :close-on-click-modal="false" @close="handleDialogClose">
                <el-form ref="form" :model="form" :rules="rules" label-width="120px">

                    <el-form-item label="姓名" prop="realname">
                        <el-input v-model="form.realname" placeholder="姓名" style="width: 80%;"></el-input>
                    </el-form-item>
                    <el-form-item label="性别" prop="sex">
                        <el-select v-model="form.sex" placeholder="请选择">
                            <el-option label="男" value="男"></el-option>
                            <el-option label="女" value="女"></el-option>
                            <el-option label="未知" value="未知"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="form.username" placeholder="用户名" style="width: 80%;"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号" prop="mobile">
                        <el-input v-model="form.mobile" placeholder="手机号码" style="width: 80%;"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱地址" prop="email">
                        <el-input v-model="form.email" placeholder="邮箱" style="width: 80%;"></el-input>
                    </el-form-item>
                    <el-row>
                        <el-col :span="7">
                            <el-form-item label="超级管理员" prop="superAdmin">
                                <el-radio-group v-model="form.superAdmin">
                                    <el-radio-button label="1">是</el-radio-button>
                                    <el-radio-button label="0">否</el-radio-button>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="7">
                            <el-form-item label="账号状态" prop="status">
                                <el-radio-group v-model="form.status">
                                    <el-radio-button :label="1">正常</el-radio-button>
                                    <el-radio-button :label="0">锁定</el-radio-button>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                    </el-row>

                </el-form>

                <div slot="footer" class="dialog-footer">
                    <el-button @click="visible = false">取 消</el-button>
                    <el-button @click="handleSubmit('form')" type="primary" :loading="submitLoading">提 交</el-button>
                </div>
            </el-dialog>

            <el-dialog title="添加角色" :close-on-click-modal="false" :visible.sync="dialogVisibleSetRole" @close="handleDialogCloseRole">

                <div style="display: flex; justify-content: center">
                    <el-transfer
                            v-loading="loadingRole"
                            v-model="roles"
                            :data="roleData"
                            :titles="['待选角色', '已选角色']"
                    ></el-transfer>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisibleSetRole=false">取 消</el-button>
                    <el-button type="primary" @click="handleSubmitSetUserRole" :loading="submitLoadingRole">确 定</el-button>
                </div>
            </el-dialog>

            <el-dialog :title="selectionRows.length > 0 ? '用户消息' : '广播消息'" :close-on-click-modal="false" :visible.sync="dialogMessageVisible" @close="handleDialogCloseMessage">
                <el-tag v-for="tag in selectionRows" :key="tag.id" closable @close="handleClose(tag)" style="margin-right: 10px;margin-bottom: 10px">
                    {{tag.realname}}
                </el-tag>
                <el-form ref="msgData" :model="msgData" :rules="rulesMsg" >
                    <el-form-item prop="title">
                        <el-input v-model="msgData.title" placeholder="标题" style="width: 80%;"></el-input>
                    </el-form-item>
                    <el-form-item prop="message">
                        <el-input type="textarea" :autosize="{ minRows: 6, maxRows: 1}" placeholder="请输入内容" v-model="msgData.message"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogMessageVisible=false">取 消</el-button>
                    <el-button type="primary" @click="handleSendMessage">确 定</el-button>
                </div>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
import { save, deleted, updated, info, list, page, selectMyPage, getRolesByUserId, setUserRole, batchResetPassword } from "@/api/admin/sysuser"
import { list as selectRoles} from '@/api/admin/sysrole'
import { toTopicMessage, toUserMessage } from "@/api/admin/sysmessage"
import { mapGetters } from 'vuex'

let msg = {
    type: null,
    mode: null,
    from: null,
    to: [],
    title: null,
    message: null
}
export default {
    computed: {
        ...mapGetters(['user'])
    },
    data() {
        return {
            visible: false,
            searchVisible: false,
            submitLoading: false,

            dataList: [],
            totalPage: 0,
            dataListLoading: true,
            selectionRows: [],

            searchForm: {
                page: 1,
                limit: 10,
                sortColumns: 'ctime,utime',
                sortType: 'desc',
                keyword: null,
                realname: null,
                username: null,
                mobile: null,
                email: null,
                status: null
            },
            form: {
                id: null,
                realname: null,
                username: null,
                password: null,
                salt: null,
                mobile: null,
                email: null,
                avatar: null,
                sex: '男',
                status: 1,
                superAdmin: 0,
                ctime: null,
                utime: null
            },
            rules: {
                realname: [
                    { required: true, message: '姓名不能为空', trigger: 'blur' }
                ],
                username: [
                    { required: true, message: '用户名不能为空', trigger: 'blur' }
                ],
                mobile: [
                    { required: true, message: '手机号码不能为空', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '邮箱不能为空', trigger: 'blur' }
                ]
            },



            roles: [],
            roleData: [],
            loadingRole: true,
            submitLoadingRole: false,
            dialogVisibleSetRole: false,

            dialogMessageVisible: false,
            msgData: Object.assign({}, msg),
            rulesMsg: {
                title: [
                    { required: true, message: '标题不能为空', trigger: 'blur' }
                ],
                message: [
                    { required: true, message: '内容不能为空', trigger: 'blur' }
                ]
            },

        }
    },
    mounted() {
    	this.$nextTick(function () {
	        this.getDataList()
    	})
    },
    methods: {
        handleSelection(selection) { // 多选
            this.selectionRows = selection
        },
        handleSizeChange(val) { // 每页数量
            this.searchForm.limit = val
            this.getDataList()
        },
        handleCurrentChange(val) { // 页码
            this.searchForm.page = val
            this.getDataList()
        },
        handleResetSearch(name) { // 重置搜索表单
            this.handleReset(name)
            this.getDataList()
        },
        handleReset(name) { // 重置表单
            const refs = this.$refs
            refs[name].resetFields()
        },
        handleSearch() { // 单条件搜索
            this.getDataList()
        },
        handleDialogClose() { //表单窗口关闭
            this.handleReset('form')
        },

        /**
         * 设置用户角色窗口
         */
        handleOpenSetRoleDialog(row) {
            this.userId = row.id
            this.dialogVisibleSetRole = true
            this.handleGetRoles()
        },
        handleDialogCloseRole(){
            this.roles = []
        },

        /**
         * 广播消息窗口
         */
        handleOpenMessageDialog() {
            if(this.selectionRows && this.selectionRows.length > 0) {
                this.msgData.title = '用户消息'
            } else {
                this.msgData.title = '广播消息'
            }
            this.dialogMessageVisible = true
        },
        handleDialogCloseMessage() {
            this.msgData = Object.assign({}, msg)
            this.$refs.table.clearSelection()
        },
		/**
         * 打开表单窗口
         */
		addOrUpdateVisible(row) {
            console.log(row);
            this.visible = true
            if (row.id) {
                this.getInfo(row.id).then(res => {
                    this.form = Object.assign({}, res.data)
                })
            } else {
                this.form.id = null
            }
        },

		/**
         * 提交表单
         */
        handleSubmit(name) {
        	const refs = this.$refs
            refs[name].validate((valid) => {
                if (valid) {
                    this.submitLoading = true
                    if (!this.form.id) {
                        save(this.form).then(res => {
                            if (this.ResultMessage(res)) {
                                this.submitLoading = false
                                this.visible = false
                                this.handleReset('form')
                                this.getDataList()
                            } else {
                                this.submitLoading = false
                            }
                        }).catch(error => {
                            this.submitLoading = false
                            this.$notify({ title: '错误', message: error, type: 'error' });
                        })
                    } else if (this.form.id) {
                        updated(this.form).then(res => {
                            if (this.ResultMessage(res)) {
                                this.submitLoading = false
                                this.visible = false
                                this.handleReset('form')
                                this.getDataList()
                            } else {
                                this.submitLoading = false
                            }
                        }).catch(error => {
                            this.submitLoading = false
                            this.$notify({ title: '错误', message: error, type: 'error' });
                        })
                    } else {
                        console.log('未知操作');
                    }
                }
            })
        },

		/**
         * 删除
         */
        handleDelete(row) {
            let ids = []
            if (row.id != undefined) {
                if (row.superAdmin) {
                    this.$notify({ title: '提示', message: '超级管理员不能删除！', type: 'warning' });
                    return
                } else {
                    ids.push(row.id)
                }
            }
            if(this.selectionRows) {
                this.selectionRows.filter((item, index) => {
                    if (item.username !== 'admin') {
                        ids.push(item.id)
                    }
                })
            }
            if (ids.length <= 0) {
                this.$notify({ title: '提示', message: '请选择需要删除的记录！', type: 'info' });
            } else {
                this.$confirm('确定要删除？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
                    deleted({ idList: ids }).then(res => {
                        if (this.ResultMessage(res)) {
                            this.getDataList()
                        }
                    }).catch(error => {
                        this.$notify({ title: '错误', message: error, type: 'error' });
                    })
                }).catch(() => {})
            }
        },

		/**
         * 详细信息
         */
        getInfo(id) {
            if (id !== undefined) {
                return info(id).then(res => {
                    if (this.ResultMessage(res, false)) {
                        return res
                    } else {
                        this.$notify({ title: '错误', message: error, type: 'error' });
                    }
                }).catch(error => {
                    this.$notify({ title: '错误', message: error, type: 'error' });
                })
            }
        },

        /**
         * 数据列表
         */
        getDataList() {
            if(this.isAuth(['admin:systemuser:list'])) {
                page(this.searchForm).then(res => {
                    if (this.ResultMessage(res, false)) {
                        this.dataList = res.data.records
                        this.totalPage = res.data.total
                        this.dataListLoading = false
                    } else {
                        this.dataListLoading = false
                    }
                }).catch(error => {
                    this.dataListLoading = false
                    this.$notify({ title: '错误', message: error, type: 'error' });
                })
            } else {
                this.dataListLoading = false
                    this.$notify({ title: '提示', message: '权限不足', type: 'warning' });
            }
        },

        /**
         * 角色列表
         */
        handleGetRoles() {
            selectRoles().then(res => {
                if (this.ResultMessage(res, false)) {
                    let data = []
                    for(let item of res.data) {
                        data.push({
                            key: item.id,
                            label: item.name
                        })
                    }
                    this.roleData = data
                    this.loadingRole = false
                } else {
                    this.loadingRole = false
                }
            }).then(() => {
                this.handleGetRolesByUserId()
            }).catch(error => {
                this.loadingRole = false
                this.$notify({ title: '错误', message: error, type: 'error' });
            })
        },

        /**
         * 根据用户ID加载用户对应的角色
         */
        handleGetRolesByUserId() {
            getRolesByUserId(this.userId).then(res => {
                if (this.ResultMessage(res, false)) {
                    if(res.data) {
                        let roles = []
                        for(let item of res.data) {
                            roles.push(item.roleId+'')
                        }
                        this.roles = roles
                    }
                }
            }).catch(error => {
                this.$notify({ title: '错误', message: error, type: 'error' });
            })
        },

        /**
         * 设置用户角色
         */
        handleSubmitSetUserRole() {
            this.submitLoadingRole = true
            const data = {"userId": this.userId, "roles": this.roles}
            setUserRole(data).then(res => {
                if (this.ResultMessage(res)) {
                    this.submitLoadingRole = false
                    this.dialogVisibleSetRole = false
                } else {
                    this.submitLoadingRole = false
                }
            }).catch(error => {
                this.submitLoadingRole = false
                this.$notify({ title: '错误', message: error, type: 'error' });
            })
        },

        /**
         * 重置密码
         */
        handleResetPassword(row) {
            let ids = []
            if(this.selectionRows) {
                this.selectionRows.filter((item, index) => {
                    if (item.username !== 'admin') {
                        ids.push(item.id)
                    }
                })
            }
            if (ids.length <= 0) {
                this.$notify({ title: '提示', message: '请选项需要重置用户登陆密码的记录！', type: 'info' });
            } else {
                this.$confirm('确定要删除？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
                    batchResetPassword({ idList: ids }).then(res => {
                        if (this.ResultMessage(res)) {
                            this.getDataList()
                        }
                    }).catch(error => {
                        this.$notify({ title: '错误', message: error, type: 'error' });
                    })
                }).catch(() => {})
            }
        },

        handleClose(tag) {
            this.selectionRows.splice(this.selectionRows.indexOf(tag), 1);
            this.$refs.table.toggleRowSelection(tag, false)
        },

        /**
         * 广播消息
         */
        handleSendMessage() {
            this.$refs.msgData.validate((valid) => {
                if (valid) {
                    if(this.selectionRows && this.selectionRows.length > 0) {
                        let toUsers = []
                        this.selectionRows.forEach(v => {
                            toUsers.push(v.id)
                        })
                        let data =  {
                            type: 'user',
                            mode: 'Notification',
                            from: this.user.id,
                            to: toUsers,
                            title: this.msgData.title,
                            message: this.msgData.message
                        }
                        this.msgData = Object.assign({}, data)
                        toUserMessage(this.msgData).then(res => {
                            if(this.ResultMessage(res)) {
                                this.dialogMessageVisible = false
                            }
                        })

                    } else {
                        let data =  {
                            type: 'topic',
                            mode: 'Notification',
                            title: this.msgData.title,
                            message: this.msgData.message
                        }
                        this.msgData = Object.assign({}, data)
                        toTopicMessage(this.msgData).then(res => {
                            if(this.ResultMessage(res)) {
                                this.dialogMessageVisible = false
                            }
                        })
                    }
                }
            })
        }
    }
}
</script>
